package xyz.ljcc.ccmt.commons.utils.converter;



import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import org.springframework.core.convert.converter.Converter;

/**
 * 字符串转日期的转换器
 * @author liucan
 *
 */
public class CustomDateConverter  implements Converter<String, Date>{

	@Override
	public Date convert(String source) {
		SimpleDateFormat sdf = null;
		String dateMat = "^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|2[0-9]|3[0-1])$";   // “yyyy-MM-dd”
		String dateTime1 = "^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|2[0-9]|3[0-1]) ([0-1][0-9]|2[0-3]):([0-5][0-9])$";  // "yyyy-MM-dd HH:mm"
		String dateTime2 = "^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|2[0-9]|3[0-1]) ([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";  // "yyyy-MM-dd HH:mm:ss"
		if(Pattern.matches(dateMat, source)){
			sdf = new SimpleDateFormat("yyyy-MM-dd");
		}else if(Pattern.matches(dateTime1, source)){
			sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		}else if(Pattern.matches(dateTime2, source)) {
			sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		}
		else{
			return null;
		}
		try {
			return sdf.parse(source);
		} catch (ParseException e) {
			return null;
		}
	}
}
